package com.swy.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@Configuration
public class FileConfig {

    @Value("${app.author.file:author/config.properties}")
    private String authorConfigFile;

    @Value("${app.sensitive-words.file:sensitive-words/sensitive-words.txt}")
    private String sensitiveWordsFile;

    @Value("${app.upload.path:uploads}")
    private String uploadDir;

    @Value("${app.logs.path:logs}")
    private String logsDir;

    @PostConstruct
    public void init() throws IOException {
        // 获取当前工作目录
        String userDir = System.getProperty("user.dir");
        log.info("当前工作目录: {}", userDir);

        // 创建作者配置目录和文件
        createAuthorConfig(userDir);

        // 创建敏感词目录和文件
        createSensitiveWordsFile(userDir);

        // 创建上传目录
        createDirectory(userDir, uploadDir);

        // 创建日志目录
        createDirectory(userDir, logsDir);
    }

    /**
     * 创建作者配置文件
     */
    private void createAuthorConfig(String userDir) throws IOException {
        Path configPath = Paths.get(userDir, authorConfigFile);
        File configFile = configPath.toFile();

        // 确保父目录存在
        if (!configFile.getParentFile().exists()) {
            configFile.getParentFile().mkdirs();
        }

        // 如果配置文件不存在，创建默认配置
        if (!configFile.exists()) {
            try (BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(configFile), StandardCharsets.UTF_8))) {
                writer.write("# 作者配置文件");
                writer.newLine();
                writer.write("username=admin");
                writer.newLine();
                writer.write("password=admin");
                writer.newLine();
            }
            log.info("创建作者配置文件: {}", configPath);
        }
    }

    /**
     * 创建敏感词文件
     */
    private void createSensitiveWordsFile(String userDir) throws IOException {
        Path wordsPath = Paths.get(userDir, sensitiveWordsFile);
        File wordsFile = wordsPath.toFile();

        // 确保父目录存在
        if (!wordsFile.getParentFile().exists()) {
            wordsFile.getParentFile().mkdirs();
        }

        // 如果敏感词文件不存在，创建空文件
        if (!wordsFile.exists()) {
            wordsFile.createNewFile();
            log.info("创建敏感词文件: {}", wordsPath);
        }
    }

    /**
     * 创建目录
     */
    private void createDirectory(String userDir, String dirName) throws IOException {
        Path dirPath = Paths.get(userDir, dirName);
        if (!Files.exists(dirPath)) {
            Files.createDirectories(dirPath);
            log.info("创建目录: {}", dirPath);
        }
    }
} 